const multer=require("multer");
const path=require("path");

module.exports = function (options={field:'file',replace:null,share:false,prefix:'photo'}) {
    if(!options.prefix)options.prefix= options.field
    
    const storage = multer.diskStorage({
        destination: (req, file, callback) => {
          callback(null, 'public/upload/');
        },
        filename: (req, file, callback) => {
          let extname=path.extname(file.originalname); 
                 
          callback(null,options.prefix + "-" + Date.now() + extname);
        },
    });
    const upload = multer({ storage }).single(options.field);  
    
    return function (req, res, next) {       
        upload(req, res, error => {
            console.log(req.query.scene)
            if (error) {        
                console.error(error); 
                let data={ status: 'fail', response: { err: '上传失败'} } 
                if(req.query.scene=='wangeditor')data={ errno: 1, message: '上传失败'} 
                res.status(500).json(data);
            } else {
                const imageUrl = `/upload/${req.file.filename}`; 
                console.log('上传:'+ imageUrl) 
                if(options.share){
                    if(options.replace){
                        req.body[options.replace]=imageUrl;
                    }else  req.body[options.field]=imageUrl;
                    next();                   
                }else{
                    let data ={ status: 'success', response: { url: imageUrl} }
                    if(req.query.scene=='wangeditor')data={errno: 0, data: {url: 'http://localhost:3000'+ imageUrl,alt: '', href: '' }}                    
                    res.json(data);
                } 
            }
        });
    }
}